package com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.repository.HddcB2GeomorphysvyprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.repository.HddcB2GeomorphysvyprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.repository.entity.HddcB2GeomorphysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.service.HddcB2GeomorphysvyprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.viewobjects.HddcB2GeomorphysvyprojecttableQueryParams;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.viewobjects.HddcB2GeomorphysvyprojecttableVO;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.entity.HddcMainafsvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.service.HddcMainafsvyregionService;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.entity.HddcTargetregionEntity;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.service.HddcTargetregionService;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.HddcWorkregionRepository;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.entity.HddcWorkregionEntity;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.service.HddcWorkregionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zyb
 * @date 2020-12-07
 */
@Service
public class HddcB2GeomorphysvyprojecttableServiceImpl implements HddcB2GeomorphysvyprojecttableService {

	@Autowired
    private HddcB2GeomorphysvyprojecttableRepository hddcB2GeomorphysvyprojecttableRepository;
    @Autowired
    private HddcB2GeomorphysvyprojecttableNativeRepository hddcB2GeomorphysvyprojecttableNativeRepository;

    @Autowired
    private HddcWorkregionService hddcWorkregionService;
    @Autowired
    private HddcTargetregionService hddcTargetregionService;
    @Autowired
    private HddcMainafsvyregionService hddcMainafsvyregionService;

    @Override
    public JSONObject queryHddcB2Geomorphysvyprojecttables(HddcB2GeomorphysvyprojecttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB2GeomorphysvyprojecttableEntity> hddcB2GeomorphysvyprojecttablePage = this.hddcB2GeomorphysvyprojecttableNativeRepository.queryHddcB2Geomorphysvyprojecttables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB2GeomorphysvyprojecttablePage);
        return jsonObject;
    }


    @Override
    public HddcB2GeomorphysvyprojecttableEntity getHddcB2Geomorphysvyprojecttable(String id) {
        HddcB2GeomorphysvyprojecttableEntity hddcB2Geomorphysvyprojecttable = this.hddcB2GeomorphysvyprojecttableRepository.findById(id).orElse(null);
        return hddcB2Geomorphysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB2GeomorphysvyprojecttableEntity saveHddcB2Geomorphysvyprojecttable(HddcB2GeomorphysvyprojecttableEntity hddcB2Geomorphysvyprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB2Geomorphysvyprojecttable.setUuid(uuid);
        hddcB2Geomorphysvyprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB2Geomorphysvyprojecttable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB2Geomorphysvyprojecttable.setIsValid("1");
        this.hddcB2GeomorphysvyprojecttableRepository.save(hddcB2Geomorphysvyprojecttable);
        return hddcB2Geomorphysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB2GeomorphysvyprojecttableEntity updateHddcB2Geomorphysvyprojecttable(HddcB2GeomorphysvyprojecttableEntity hddcB2Geomorphysvyprojecttable) {
        UpdateUtil.copyNullProperties(hddcB2GeomorphysvyprojecttableRepository.findByUuidAndIsValid(hddcB2Geomorphysvyprojecttable.getUuid(), "1"), hddcB2Geomorphysvyprojecttable);
        hddcB2Geomorphysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB2Geomorphysvyprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB2GeomorphysvyprojecttableRepository.save(hddcB2Geomorphysvyprojecttable);
        return hddcB2Geomorphysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB2Geomorphysvyprojecttables(List<String> ids) {
        List<HddcB2GeomorphysvyprojecttableEntity> hddcB2GeomorphysvyprojecttableList = this.hddcB2GeomorphysvyprojecttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB2GeomorphysvyprojecttableList) && hddcB2GeomorphysvyprojecttableList.size() > 0) {
            for(HddcB2GeomorphysvyprojecttableEntity hddcB2Geomorphysvyprojecttable : hddcB2GeomorphysvyprojecttableList) {
//                this.hddcB2GeomorphysvyprojecttableRepository.delete(hddcB2Geomorphysvyprojecttable);
                hddcB2Geomorphysvyprojecttable.setIsValid("0");
                hddcB2Geomorphysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB2Geomorphysvyprojecttable.setUpdateTime(new Date());
                this.hddcB2GeomorphysvyprojecttableRepository.save(hddcB2Geomorphysvyprojecttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB2GeomorphysvyprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB2GeomorphysvyprojecttableEntity> yhDisasterEntities = hddcB2GeomorphysvyprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB2GeomorphysvyprojecttableVO> list=new ArrayList<>();
        for (HddcB2GeomorphysvyprojecttableEntity entity:yhDisasterEntities) {
            HddcB2GeomorphysvyprojecttableVO yhDisasterVO=new HddcB2GeomorphysvyprojecttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"微地貌测量工程","微地貌测量工程",HddcB2GeomorphysvyprojecttableVO.class,"微地貌测量工程.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB2GeomorphysvyprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB2GeomorphysvyprojecttableVO.class, params);
            List<HddcB2GeomorphysvyprojecttableVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB2GeomorphysvyprojecttableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB2GeomorphysvyprojecttableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }



    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcB2GeomorphysvyprojecttableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB2GeomorphysvyprojecttableEntity yhDisasterEntity = new HddcB2GeomorphysvyprojecttableEntity();
            HddcB2GeomorphysvyprojecttableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB2Geomorphysvyprojecttable(yhDisasterEntity);
        }
    }

    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcB2GeomorphysvyprojecttableEntity> listAll = hddcB2GeomorphysvyprojecttableRepository.findByAll();
        ArrayList<String> list = new ArrayList<>();
        for (HddcB2GeomorphysvyprojecttableEntity b2All: listAll) {
            if (!list.contains(b2All.getWorkregionid())&&!StringUtils.isEmpty(b2All.getWorkregionid())){
                list.add(b2All.getWorkregionid());
            }
        }
        if(null == list || list.size() ==0){
            return 1;
        }
        for (String id:list) {
            String str="";
            HddcWorkregionEntity hddcWorkregionEntity =  hddcWorkregionService.findById(id);
            if (hddcWorkregionEntity==null){
                hddcB2GeomorphysvyprojecttableRepository.updateStatus("2","质检失败！",id);
                continue;
            }
            int total1=0;
            int total2=0;
            for (HddcB2GeomorphysvyprojecttableEntity b2All: listAll) {
                if (!StringUtils.isEmpty(b2All.getWorkregionid())&& b2All.getWorkregionid().equals(id)){
                    if(b2All.getCollectedsamplecount()!=null && !b2All.getCollectedsamplecount().equals("")){
                        total1+= b2All.getCollectedsamplecount();
                    }
                    if(b2All.getSamplecount()!=null &&! b2All.getSamplecount().equals("")){
                        total2+= b2All.getSamplecount();
                    }
                }
            }
            if(!(total1==hddcWorkregionEntity.getCollectedsamplecount())){
                //System.out.println( id +"采样总数失败");
               str += "采样总数失败.";

            }
            if(!(total2==hddcWorkregionEntity.getSamplecount())){
                //System.out.println( id +"送样总数失败");
                str+= "送样总数失败";
            }
            if(str.isEmpty()){
                str +="质检成功";
                hddcB2GeomorphysvyprojecttableRepository.updateStatus("1",str,id);
            }else{
                hddcB2GeomorphysvyprojecttableRepository.updateStatus("2",str,id);
            }

        }
        return 1;
    }

    @Override
    @Transactional
    public int mbdataQualityCheck() {
        List<HddcB2GeomorphysvyprojecttableEntity> listAll = hddcB2GeomorphysvyprojecttableRepository.findByAll();
        ArrayList<String> list = new ArrayList<>();
        for (HddcB2GeomorphysvyprojecttableEntity b2All: listAll) {
            if (!list.contains(b2All.getTargetregionid())&&!StringUtils.isEmpty(b2All.getTargetregionid())){
                list.add(b2All.getTargetregionid());
            }
        }
        if(null == list || list.size() ==0){
            return 1;
        }
        for (String id:list) {
            String str="";
            HddcTargetregionEntity hddcTargetregionEntity =  hddcTargetregionService.findById(id);
            if (hddcTargetregionEntity==null){
                hddcB2GeomorphysvyprojecttableRepository.updateStatus2("2","质检失败",id);
                continue;
            }
            int total1=0;
            int total2=0;
            for (HddcB2GeomorphysvyprojecttableEntity b2All: listAll) {
                if (!StringUtils.isEmpty(b2All.getTargetregionid())&& b2All.getTargetregionid().equals(id)){
                    if(b2All.getCollectedsamplecount()!=null && !b2All.getCollectedsamplecount().equals("")){
                        total1+= b2All.getCollectedsamplecount();
                    }
                    if(b2All.getSamplecount()!=null &&! b2All.getSamplecount().equals("")){
                        total2+= b2All.getSamplecount();
                    }
                }
            }
            if(!(total1==hddcTargetregionEntity.getCollectedsamplecount())){
                //System.out.println( id +"采样总数失败");
                str += "采样总数失败.";

            }
            if(!(total2==hddcTargetregionEntity.getSamplecount())){
                //System.out.println( id +"送样总数失败");
                str+= "送样总数失败";
            }
            if(str.isEmpty()){
                str +="质检成功";
                hddcB2GeomorphysvyprojecttableRepository.updateStatus2("1",str,id);
            }else{
                hddcB2GeomorphysvyprojecttableRepository.updateStatus2("2",str,id);
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int zhdataQualityCheck() {
        List<HddcB2GeomorphysvyprojecttableEntity> listAll = hddcB2GeomorphysvyprojecttableRepository.findByAll();
        ArrayList<String> list = new ArrayList<>();
        for (HddcB2GeomorphysvyprojecttableEntity b2All: listAll) {
            if (!list.contains(b2All.getMainafsregionid())&&!StringUtils.isEmpty(b2All.getMainafsregionid())){
                list.add(b2All.getMainafsregionid());
            }
        }
        if(null == list || list.size() ==0){
            return 1;
        }
        for (String id:list) {
            String str="";
            HddcMainafsvyregionEntity hddcMainafsvyregionEntity =  hddcMainafsvyregionService.findbyId(id);
            if (hddcMainafsvyregionEntity==null){
                hddcB2GeomorphysvyprojecttableRepository.updateStatus3("2","质检失败",id);
                continue;
            }
            int total1=0;
            int total2=0;
            for (HddcB2GeomorphysvyprojecttableEntity b2All: listAll) {
                if ( !StringUtils.isEmpty(b2All.getMainafsregionid())&& b2All.getMainafsregionid().equals(id)){
                    if(b2All.getCollectedsamplecount()!=null && !b2All.getCollectedsamplecount().equals("")){
                        total1+= b2All.getCollectedsamplecount();
                    }
                    if(b2All.getSamplecount()!=null &&! b2All.getSamplecount().equals("")){
                        total2+= b2All.getSamplecount();
                    }
                }
            }
            if(!(total1==hddcMainafsvyregionEntity.getCollectedsamplecount())){
                //System.out.println( id +"采样总数失败");
                str += "采样总数失败.";

            }
            if(!(total2==hddcMainafsvyregionEntity.getSamplecount())){
                //System.out.println( id +"送样总数失败");
                str+= "送样总数失败";
            }
            if(str.isEmpty()){
                str +="质检成功";
                hddcB2GeomorphysvyprojecttableRepository.updateStatus3("1",str,id);
            }else{
                hddcB2GeomorphysvyprojecttableRepository.updateStatus3("2",str,id);
            }
        }
        return 1;
    }


}
